/**
 * @desc 封装微信工具 - 网络请求
 * @author chend
 */
class Http {
  constructor() {
    this.requestCount = 0
  }

  /**
   * 网络状态码处理
   * @param {*} code
   * @param {*} message
   */
  interceptors(resolve, reject, res) {
    const { data } = res
    if ((Number(data.status) || res.statusCode) !== 200) {
      this.errorHandler(reject, data.desc)
    } else {
      this.hideLoading()
      resolve(data)
    }
  }

  /**
   * 接口请求错误处理
   * @param {Promise} reject
   * @param {*} err
   */
  errorHandler(reject, err) {
    console.log(err)
    this.hideLoading()
    wx.showToast({
      title: '请求失败！',
      icon: 'none',
      mask: true,
      success: () => {
        reject(err)
      }
    })
  }

  showLoading() {
    this.requestCount++;
    if (this.requestCount === 1) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    }
  }

  hideLoading() {
    this.requestCount--;
    if (this.requestCount === 0) {
      wx.hideLoading()
    }
  }

  /**
   * 去除空参数
   */
  removeEmptyParam(object) {
    for (let o in object) {
      if (['', undefined, 'undefined', null, 'null'].includes(object[o])) {
        delete object[o]
      }
    }
    return object
  }

  /**
   * GET请求
   * @param {*} url - 请求url
   * @param {*} params - 请求数据
   */
  get(url, params) {
    this.showLoading()
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: params,
        method: 'GET',
        header: {
          Accept: 'application/json, text/plain, */*',
          Cookie: `SHRIOSESSIONID=${wx.getStorageSync('sessionId')}`
        },
        success: res => this.interceptors(resolve, reject, res),
        fail: err => this.errorHandler(reject, err)
      })
    })
  }
  /**
   * POST请求
   * @param {*} url - 请求url
   * @param {*} params - 请求数据
   */
  post(url, params, contentType = '') {
    this.showLoading()
    return new Promise((resolve, reject) => {
      params = this.removeEmptyParam(params)
      wx.request({
        url: url,
        data: params,
        method: 'POST',
        header: {
          Accept: 'application/json, text/plain, */*',
          Cookie: `SHRIOSESSIONID=${wx.getStorageSync('sessionId')}`,
          'content-type': contentType
        },
        success: res => this.interceptors(resolve, reject, res),
        fail: err => this.errorHandler(reject, err)
      })
    })
  }

  /**
   * 使用默认header的请求
   * @param {} url
   * @param {*} data
   */
  request(url, data) {
    this.showLoading()
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        data,
        success: res => this.interceptors(resolve, reject, res),
        fail: err => this.errorHandler(reject, err)
      })
    })
  }
}

export default new Http()
